//
//  NetWorkTool.swift
//  Sina
//
//  Created by 管观荣 on 15/9/24.
//  Copyright © 2015年 CHer. All rights reserved.
//

import UIKit
import AFNetworking

enum RequstMethod:String{
    case GET = "GET"
    case POST = "POST"
}

// OC 的 typedefine 非常类似，定义数据类型
// 网络请求完成回调的数据类型 - 首字母要大写
typealias RequestFinishedCallBack = (result: AnyObject?, error: NSError?) -> ()

class NetWorkTool: AFHTTPSessionManager {

    //网络请求单例
    static let sharedTool : NetWorkTool = {
        
        let instance = NetWorkTool(baseURL: nil);
        
        instance.responseSerializer.acceptableContentTypes?.insert("text/plain")
        
        return instance;
    }()
    
    // MARK: - 应用程序信息
    private let appKey = "3763573571"
    private let appSecret = "d3e7a54be3676c0d067f252fa5d47c07"
    /// 授权回调地址
    let redirectURI = "http://www.baidu.com"
    
    //oauth登录URL
    var oauthURL:NSURL {
        let urlString = "https://api.weibo.com/oauth2/authorize?client_id=\(appKey)&redirect_uri=\(redirectURI)"
        
        return NSURL(string: urlString)!
    }
    // MARK: - 创建 token 字典
    /// 目前有很多公司，都会封装自己的网络访问方法，会把用户身份安全的代码全部封装！
    private var tokenParams: [String: AnyObject]? {
        // 1. 判断用户账户中是否存在token，如果没有存在说明用户没有登录，或者 token 过期
        guard let token = UserAccountViewModel.sharedAccountViewModel.userAccount?.access_token else {
            // token 不存在
            return nil
        }
        
        // 2. 返回 token 字典
        return ["access_token": token]
    }
    /// 加载微博数据
    ///
    /// - parameter finished: 完成回调
    /// - see: [http://open.weibo.com/wiki/2/statuses/home_timeline](http://open.weibo.com/wiki/2/statuses/home_timeline)
    func loadHome(finished: RequestFinishedCallBack) {
        // 1. 建立 token 字典
        guard let params = tokenParams else {
            // 如果 token 为 nil，需要通知控制器，不再执行网络方法
            finished(result: nil, error: NSError(domain: "cn.itcast.error", code: -1002, userInfo: ["message": "token 为 nil"]))
            return
        }
        
        // 2. 发起网络请求
        request(.GET, urlString: "https://api.weibo.com/2/statuses/home_timeline.json", parameters: params, finished: finished)
    }

    /// 加载用户
    /// - see: [http://open.weibo.com/wiki/2/users/show](http://open.weibo.com/wiki/2/users/show)
    func loadUserInfo(uid: String, finished: RequestFinishedCallBack) {
        
        // 1. 建立 token 字典
        guard var params = tokenParams else {
            // 如果 token 为 nil，需要通知控制器，不再执行网络方法
            finished(result: nil, error: NSError(domain: "cn.itcast.error", code: -1002, userInfo: ["message": "token 为 nil"]))
            return
        }
        
        // 2. 向字典中增加参数
        params["uid"] = uid
        
        // 2. 发起网络请求
        request(.GET, urlString: "https://api.weibo.com/2/users/show.json", parameters: params, finished: finished)
    }

    /// 使用 code 加载 token

    func loadAccessToken(code: String, finished: RequestFinishedCallBack) {
        let params = ["client_id": appKey,
            "client_secret": appSecret,
            "grant_type": "authorization_code",
            "code": code,
            "redirect_uri": redirectURI]
        
        request(.POST, urlString: "https://api.weibo.com/oauth2/access_token", parameters: params, finished: finished)
     }
    
    //网络请求封装
    private func request(method: RequstMethod, urlString: String, parameters: [String: AnyObject]?, finished: RequestFinishedCallBack) {
        
        // 闭包是提前准备好的代码，可以当作参数传递
        let success = { (task: NSURLSessionDataTask, result: AnyObject) -> () in
            finished(result: result, error: nil)
        }
        let failure = { (task: NSURLSessionDataTask, error: NSError) -> () in
            print(error)
            finished(result: nil, error: error)
        }
        
        if method == RequstMethod.GET {
            GET(urlString, parameters: parameters, success: success, failure: failure)
        } else {
            POST(urlString, parameters: parameters, success: success, failure: failure)
        }
    }

}
